/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package view.HTMLUIcomponents;

import java.util.ArrayList;

import model.Labels;
import model.Vocabulary;

import org.apache.commons.lang.StringEscapeUtils;
import org.openrdf.model.URI;

import controller.HelperFunctions;
import controller.elementMapper.Mapper;


public class Videos extends AbstractComponent {
	

	public static final String CSSIDFIELD = "divvideos";
	public static final String CSSIDCONTENT = "divvideoscontent";
	public static final String NAMEFORMELEMENT = "youTubeVideosEntry";
	
	public static final String FOCUSIDOFEDITPANEL = NAMEFORMELEMENT + "_input";
	

	public static String getEmptyFieldContainer() {

		String ret = AbstractComponent.getEmptyFieldContainer( CSSIDFIELD );
		
		return ret;
	}
	
	public static String getLinkToShowSecondaryFieldInEditMode( boolean shownavigationInEditField ) {
				
		return getLinkToShowSecondaryFieldInEditMode( CSSIDFIELD, shownavigationInEditField, Labels.VIDEOS.getNamePlural() );
	}
	
	/**
	 * Returns the field in view mode.
	 * @param id
	 * @param entry
	 * @return
	 */
	public static String getFieldInViewMode(  URI uri, boolean showNavigation, boolean showNavigationInEditMode ) throws Exception {
		String ret = "";

		ret += getTitleContainer( model.Labels.VIDEOS, false, true );
		
		ret += getFormContainer( getFormInViewMode( uri, showNavigation, showNavigationInEditMode ), CSSIDCONTENT );

		// The field is printed in <div id=" fieldIdentifier "> and hence all its components can be accessed with this
		ret = getFieldContainer( ret, CSSIDFIELD );
		
		return ret;
	}
	
	/**
	 * Returns the field in view mode.
	 * @param id
	 * @param entry
	 * @return
	 */
	public static String getFieldInEditMode(  URI uri, String entry, ArrayList<Exception> exceptions, boolean showNavigation ) throws Exception {
		String ret = "";
		
		ret += getContentInEditMode(uri, entry, exceptions, showNavigation);

		// The field is printed in <div id=" fieldIdentifier "> and hence all its components can be accessed with this
		ret = getFieldContainer( ret, CSSIDFIELD );
		
		return ret;
	}

	public static String getContentInEditMode(  URI uri, String entry, ArrayList<Exception> exceptions, boolean showNavigation ) throws Exception {
		String ret = "";
		
		ret += getTitleContainer( model.Labels.VIDEOS, false, true );		
		ret += getFormContainer( getFormInEditMode( uri, entry, exceptions, showNavigation ), CSSIDCONTENT );
		
		return ret;
	}
	
	public static String getFormInViewMode( URI uri, boolean showNavigation, boolean showNavigationInEditMode ) throws Exception {

		String ret = "";	

		java.util.ArrayList<String> list = Mapper.selectVideos( uri );
		String content = getYoutubeVideosHTML(list);	

		ret = renderViewForm( 
				content, 
				Mapper.selectHasVersionDateTimeString(uri),
				CSSIDCONTENT, 
				showNavigation,
				showNavigationInEditMode );
		
		return ret;
	}
	

	private static String getYoutubeVideosHTML( ArrayList<String> entry ) throws Exception {
		String ret = "";
		
		if( entry!=null ) {
			
			for( int i = 0; i<entry.size(); i++ ) {

					
				String id = entry.get(i);
				String src = "";
				
				org.w3c.dom.Document document = HelperFunctions.ParseYouTubeRESTget_details(id);
				
				org.w3c.dom.NodeList list = document.getFirstChild().getFirstChild().getChildNodes();
				Boolean found = false;
				Boolean found2 = false;
				String author = "";
				int j = 0;
				while( ( found==false || found2==false ) && j < list.getLength() ) {
					if( list.item( j ).getNodeName().equals("author")) {
						author = list.item(j).getTextContent();
						logger.debug( "author found:" + author);
						found = true;
					}		
					else if( list.item( j ).getNodeName().equals("thumbnail_url")) {
						src = list.item(j).getTextContent();
						logger.debug( "src found:" + src);
						found2 = true;
					}						
					j++;
				}

				String onmouseoverevent = StringEscapeUtils.escapeHtml( "youTubeTip('<object><param name=\\'movie\\' value=\\'http://www.youtube.com/v/"+id+"\\'></param><embed src=\\'http://www.youtube.com/v/"+id+"\\' type=\\'application/x-shockwave-flash\\' wmode=\\'transparent\\' ></embed></object><br />Author (YouTube User): " + author + "')" );
				
				ret += "<img class=\"flickrImage\" src=\"" + src + "\" alt=\"" + src + "\" onmouseover=\"" + onmouseoverevent + "\" onclick=\"javascript:toggleBackground(document.getElementById(\'"+id+"\'));\" />"; // WITHOUT "\n" !!!
				
				// String onmouseoverevent = "myTip('Author (YouTube User): " + author + "')";
				
				// ret += "<span class=\"spanVideo\"><a onmouseover=\"" + onmouseoverevent + "\"><object><param name='movie' value='http://www.youtube.com/v/"+id+"'></param><embed src='http://www.youtube.com/v/"+id+"' type='application/x-shockwave-flash' wmode='transparent' ></embed></object></span>";

			}
		}
		
		if( ret.equals("") )
			ret = NOTHINGSELECTED;
		
		return ret;	
	}

	
	
	

	
	public static String getFormInEditMode( URI uri, String entry, ArrayList<Exception> exceptions, boolean showNavigation ) throws Exception {
		
		String ret = "";

		String actualVersionContent = NOTHINGSELECTED;
		String actualTimestamp = Mapper.selectHasVersionDateTimeString(uri);
		
		if( uri!=null ) {
			
			ArrayList<String> tmp = Mapper.selectVideos( uri );			
			if( tmp!=null ) {
				actualVersionContent = getYoutubeVideosHTML( tmp );
			}
		}

		if(entry==null)
			entry="";

		String content = getYoutubeVideosEditHTML( entry, Mapper.selectLabel( uri, Vocabulary.ENGLISH) );
		

		ret = renderEditForm( 
				Labels.TRANSLATIONS, 
				content,
				exceptions, 
				actualVersionContent, 
				actualTimestamp,
				CSSIDCONTENT, 
				NAMEFORMELEMENT, 
				showNavigation );


		return ret;
	}
	
	private static String getYoutubeVideosEditHTML( String entry, String fill ) throws Exception {

		String ret = "";

		if( fill==null )
			fill = "";
		
		

		// #########################################
		
		String selectedContent = 
			"	<div id=\"" + NAMEFORMELEMENT + "_act\" >"; // WITHOUT "\n" !!!

		// the actual values
		String[] strarray = entry.split( HelperFunctions.DEFAULTPLITTER );
		for( int i = 0; i<strarray.length; i++ ){

			if( !strarray[i].equals("") ) {
				String id = strarray[i];
				String src = "";
				
				org.w3c.dom.Document document = HelperFunctions.ParseYouTubeRESTget_details(id);
				
				org.w3c.dom.NodeList list = document.getFirstChild().getFirstChild().getChildNodes();
				Boolean found = false;
				int j = 0;
				while( found==false && j<list.getLength() ) {
					if( list.item( j ).getNodeName().equals("thumbnail_url")) {
						src = list.item(j).getTextContent();
						found = true;
					}					
					j++;
				}	

				selectedContent += getImageHTML(
						id, 
						src, 
						"youTubeTip('<object><param name=\\'movie\\' value=\\'http://www.youtube.com/v/"+id+"\\'></param><embed src=\\'http://www.youtube.com/v/"+id+"\\' type=\\'application/x-shockwave-flash\\' wmode=\\'transparent\\' ></embed></object>')", 
						"toggleBackground(document.getElementById(\'"+id+"\'));toggleBackground(this);hideDeleteButtonIfNothingSelected('"+NAMEFORMELEMENT + "_act','"+NAMEFORMELEMENT + "_deletebuttonid');return false;" );
			}
		}
		
				
				
		selectedContent +=
			"	</div>\n";

		// #########################################
		// #########################################
		
		
		String addContent = 
			"	<div>\n";

		addContent += getDeleteButton(NAMEFORMELEMENT);
			
		
		addContent +=
			"		<div class=\"addcontainer\">\n";
		// the selectable items:
		addContent += 
			"<input type=\"radio\" name=\"videoRadio\" id=\"youTubeFulltext\" value=\"youTubeFulltext\" checked=\"checked\">Fulltext" +
			"<input type=\"radio\" name=\"videoRadio\" id=\"youTubeUri\" value=\"youTubeUri\"><a href=\"http://www.youtube.com/\" onmouseover=\"myTip('Any page in YouTube which shows a video.')\" target=\"_blank\">YouTube Videopage</a> (URI)" +
			"<br />\n" +
			" <input style=\"width: 200px;\" type=\"text\" " +
			"onkeypress=\"if((event.keyCode==13)){document.getElementById('youTubeButton').click();}\" " +
			"onblur=\"onkeyup();\" onkeyup=\"" +
				"if( this.value.trim()!='' ) " +
					"document.getElementById('youTubeButton').disabled=false; " +
				"else " +
					"document.getElementById('youTubeButton').disabled=true;" +
			"\" " +
			"autocomplete=\"off\" value=\""  + fill + "\" size=\"60\" id=\"" + NAMEFORMELEMENT + "_input\">";
		addContent +=
			"	<input type=\"button\" ";
		if( fill.equals("") )
			addContent += "disabled=\"true\" ";				
		addContent += 	
			"value=\"YouTube Search**\" id=\"youTubeButton\" onclick=\"" +
			"	var selVal=GetSelectedRadioValue(document.getElementsByName('videoRadio'));" +
			"	if(selVal==document.getElementById('youTubeFulltext').value){" +
			"		searchYouTubeVideos('"+NAMEFORMELEMENT+"_sel',document.getElementById('" + NAMEFORMELEMENT + "_input').value," + model.DHTMLConstants.SEARCHYOUTUBEBYTAGS + ");" +
			"	} else if(selVal==document.getElementById('youTubeUri').value){" +
			"		extractVideoId('"+NAMEFORMELEMENT+"_sel',document.getElementById('" + NAMEFORMELEMENT + "_input').value," + model.DHTMLConstants.SEARCHYOUTUBEBYID + ");" +
			"	}"+
			"\">";
		addContent += 
			"			<div class=\"inputhint\">Input text which describes the searched best (or the URI of a YouTube video).</div>\n";
		addContent += 
			"			<div id=\"" + NAMEFORMELEMENT + "_sel\"></div>\n";
		addContent += 
			"		</div>\n";
		addContent +=
			"	</div>\n";
		
		addContent += 
			"	<div class=\"clearer\">&nbsp;</div>\n";

			// #########################################
			// #########################################

		
		ret = selectedContent + addContent;
		
		
		
		
		
		// the actual values (again; this field is filled / decreased with DHTML but has to be "initialized")
		ret +=
			"<input type=\"hidden\" name=\"" + NAMEFORMELEMENT + "\" value=\"" + entry + "\" />\n";
		
		return ret;
	}

	// used for flickr and youtube to get the preview.
	private static String getImageHTML( String id, String imgSrc, String onmouseoverevent, String onclickevent ){
		
		return "<span id=\"" + id + "\" class=\"selectedElement selectedImage\"><img src=\"" + imgSrc + "\" class=\"spanImageThumb\" onmouseover=\"" + onmouseoverevent + "\" onclick=\"" + onclickevent + "\"/></span>"; // WITHOUT "\n" !!!
		
	}
}
